<template>
  <div>
    <CustomForm :customFields="findPasswordFields" :handleSubmit="submit" />
  </div>
</template>

<script setup lang="ts">
import CustomForm from './basicForm.vue';
import { GoPageName, Icons } from "@/enums/index.ts"
import { LoginData } from "@/api/login/types"
import { encryptedData } from "@/utils/jsencrypt"
import LoginApi from "@/api/login/index"
import { useUserInfoStore } from '@/stores/info/index' // 登陆状态获取，全局变量
import { Cookie, Session } from "@/utils/cookieSet"
const userInfoStore = useUserInfoStore();
const useLoginApi = LoginApi

// 登陆函数,负责对接接口
const submit = (data: LoginData): Promise<any> => {
  return new Promise((resolve, reject) => {
    // 加密密码
    const encryptedPassword = encryptedData(data.password);
    if (!encryptedPassword) {
      reject(new Error('密码加密失败'));
      return;
    }

    // 构建加密后的登录数据
    const loginData = {
      ...data,
      password: encryptedPassword
    };
    
    // 登录接口
    useLoginApi.login(loginData).then((res) => {
      userInfoStore.setIsLogin(true)
      userInfoStore.setUserInfo(res.data)
      Cookie.setCookies('token', res.data.token)
      Session.set('account', res.data.account)
      resolve(res)
    }).catch((err) => {
      reject(err)
    });
  });
}


// 传给自定义组件的参数
const findPasswordFields = {
  title: '账号登录',
  btnTitle: "登录",
  type: GoPageName.LOGIN,
  inputData: [
    {
      lable: "account", value: "", inputPlaceholder: '请输入用户名', type: "text", icon: Icons.USER
    },
    {
      lable: "password", value: "", inputPlaceholder: '请输入密码', type: "password", icon: Icons.LOCK
    },
  ],
  rules: [
    [{ required: true, message: '请检查用户名是否正确', trigger: 'blur' },],
    [{ required: true, message: '请检查密码', trigger: 'blur' },]
  ],
};
</script>
